package com.libui

import android.content.Context
import android.util.Log
import com.libbase.Weak
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import com.tencent.smtt.sdk.TbsListener

class LibUI {
    interface DataSource {
        val htmlPath: String

        val lottiePath: String

        val imagePath: String
    }

    interface Adapter {
        fun push(url: String, params: Any?): Boolean

        fun tracking(event: String, params: Map<String, Any>?)

        fun onWebViewMessage(messageId: String, params: Map<String, Any>?)

    }

    companion object {
        const val TAG: String = "LibUI"
        val instance: LibUI by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            LibUI()
        }
    }

    var dataSource: DataSource? by Weak()

    var adapter: Adapter? by Weak()

    fun initLib(dataSource: DataSource, adapter: Adapter) {
        this.dataSource = dataSource
        this.adapter = adapter
    }

    fun initQbSdk(context: Context) {
        /* 设置允许移动网络下进行内核下载。默认不下载，会导致部分一直用移动网络的用户无法使用x5内核 */
        QbSdk.setDownloadWithoutWifi(true)

        val map: Map<String, Any> = mapOf(
            TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER to true,
            TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE to true,
        )
        QbSdk.initTbsSettings(map)

        /* SDK内核初始化周期回调，包括 下载、安装、加载 */
        QbSdk.setTbsListener(object : TbsListener {
            override fun onDownloadFinish(stateCode: Int) {
                Log.i(TAG, "QbSdk onDownloadFinish: $stateCode")
            }

            override fun onInstallFinish(stateCode: Int) {
                Log.i(TAG, "QbSdk onInstallFinish: $stateCode")
            }

            override fun onDownloadProgress(progress: Int) {
                Log.i(TAG, "QbSdk onDownloadProgress: $progress")
            }
        })

        /* 此过程包括X5内核的下载、预初始化，接入方不需要接管处理x5的初始化流程，希望无感接入 */
        QbSdk.initX5Environment(context, object : QbSdk.PreInitCallback {
            override fun onCoreInitFinished() {
                Log.i(TAG, "QbSdk onCoreInitFinished")
            }

            override fun onViewInitFinished(isX5: Boolean) {
                Log.i(TAG, "QbSdk onViewInitFinished: $isX5")
            }
        })
    }
}